package com.bfly.mall.product.api;

import com.bfly.common.ResponseUtil;
import com.bfly.core.base.controller.BaseController;
import com.bfly.core.base.entity.ResponseData;
import com.bfly.core.security.ActionModel;
import com.bfly.mall.product.dto.ProductCommentFormDTO;
import com.bfly.mall.product.entity.ProductComment;
import com.bfly.mall.product.dto.ProductCommentListDTO;
import com.bfly.mall.product.enums.ProductCommentStatusEnum;
import com.bfly.mall.product.service.IProductCommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品评论APIController
 *
 * @author 长沙商脉科技有限公司
 * @date 2020/11/1 10:47
 */
@RestController
@RequestMapping(value = "/api/product/comment")
public class ProductCommentApiController extends BaseController {

    @Autowired
    private IProductCommentService commentService;

    /**
     * 评论列表
     * @author 长沙商脉科技有限公司
     * @date 2020/11/1 10:49
     */
    @GetMapping(value = "/list")
    public void listComment(HttpServletResponse response, @RequestParam(value = "productId",defaultValue = "0")int productId) {
        Map<String,Object> param=new HashMap<>();
        param.put("product_id",productId);
        param.put("status",ProductCommentStatusEnum.PASS.getId());
        param.put("is_poster",true);
        List<ProductComment> comments = commentService.getList(param);
        List<ProductCommentListDTO> list = new ArrayList<>();
        if (comments != null) {
            for (ProductComment comment : comments) {
                ProductCommentListDTO dto = new ProductCommentListDTO();
                BeanUtils.copyProperties(comment, dto);
                list.add(dto);
            }
        }
        ResponseUtil.writeJson(response, ResponseData.getSuccess(list));
    }

    /**
     * 发布评论
     * @author 长沙商脉科技有限公司
     * @date 2020/12/31 13:12
     */
    @PostMapping(value = "/add")
    @ActionModel("发布评论")
    public void addComment(HttpServletResponse response, @Valid @RequestBody ProductCommentFormDTO formDTO, BindingResult result){
        validData(result);
        commentService.save(getUser(),formDTO);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(""));
    }
}